<!--
@description:
@author: ldb
@time: 2022-11-24 13:52:46
-->
<template>
  <a-form
    ref="baseForm"
    :model="formState"
    :label-col="{ span: 3 }"
    :wrapper-col="{ span: 24 }"
    autocomplete="off"
    @finish="form.onFinish(beforeSubmit)"
    @finishFailed="form.onFinishFailed"
  >
    <base-form-item
      v-for="item in formItems"
      :key="item.name"
      v-model:value="formState[item.name]"
      v-bind="item"
      @extraUpdate="extraUpdate"
    />
    <a-form-item v-show="type !== 1" :wrapper-col="{ span: 24, offset: 10 }">
      <a-button type="primary" html-type="submit">确认</a-button>
      <a-button style="margin-left: 10px" @click="form.cancel">取消</a-button>
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
import { defineProps, reactive, onMounted } from 'vue'
import { useForm } from '@/hooks/base/FormHooks'
import { formItems } from './forms'
import { injectCustomUpdateOptions } from '@/utils/form-item-util'
import { DEPT_API_PRE_SUFFER, deptSelected } from '@/api/system/dept'
import { roleSelected } from '@/api/system/role'
import { Dept, RoleDept } from '@/entity/system/dept'
const props = defineProps<{ id: string; type: number }>()
const formState = reactive<Partial<Dept>>({})
const form = useForm(DEPT_API_PRE_SUFFER, formState, props, formItems)
onMounted(async () => {
  form.init(() => {
    if (formState?.sysRole) {
      formState.sysRoleDept = formState?.sysRole.map((val) => val.id) as unknown as Array<RoleDept>
    }
  })
  await injectCustomUpdateOptions(formItems.value, 'sysRoleDept', roleSelected)
  await injectCustomUpdateOptions(formItems.value, 'parentId', deptSelected)
})

async function extraUpdate(name: string, value: Array<string>, extraValue: Array<Dept>) {
  if (name === 'parentId') {
    formState.sysRoleDept = undefined
    formState.parentName = extraValue ? extraValue[0].name : ''
  }
  await injectCustomUpdateOptions(formItems.value, 'sysRoleDept', roleSelected)
}

/**
 * 提交之前
 */
function beforeSubmit() {
  if (formState.parentId) {
    formState.parentId = formState.parentId[0]
  }
  if (formState.sysRoleDept) {
    formState.sysRoleDept = formState.sysRoleDept.map((val) => {
      return {
        roleId: val,
      }
    }) as unknown as Array<RoleDept>
  }
}
</script>

<style scoped lang="scss"></style>
